package com.ebai.product.management.base.utils;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.HashMap;
import java.util.List;

/**
 * 针对存储SQL的XML解析基类
 * @author xsding@vip.qq.com
 *
 */
public class QueryXmlParse {
	
	private static Logger logger = Logger.getLogger(QueryXmlParse.class);

	public static Document getXml(String path) {
		// xmlcache.xml 对应的 document
		Document documentXML = null;
		try {
			// xmlcache.xml 中结点值xml 对应的 document
			Resource resource = null;
			SAXReader saxReader = new SAXReader();
			saxReader.setValidation(false);
			saxReader.setIgnoreComments(true);
			// 读取存放xml的资源文件
			resource = new ClassPathResource(path);
			documentXML = saxReader.read(resource.getInputStream());
		}
		catch (Exception e) {
			if (logger.isInfoEnabled()) {
				logger.info("获取XML（" + path + "）文件失败！");
				e.printStackTrace();
			}
		}
		return documentXML;
	}

	/**
	 * 读取统计SQL的模板
	 * 
	 * @param path
	 * @param xpath
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Deprecated
	public static HashMap<String, String> readReportSql(String path, final String xpath) {
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			// 解析节点 getXml(path)
			List listx = getXml(path).selectNodes(xpath);// "/systemLoad/value"
			if (listx != null && !listx.isEmpty()) {

				// logger.debug("获取XML配置文件节点数为：" + listx.size());

				for (int i = 0; i < listx.size(); i++) {
					Element el = (Element) listx.get(i);
					String sql = el.getTextTrim();
					String key = el.attributeValue("key").trim();
					if (key != null && !"".equals(key) && sql != null && !"".equals(sql)) {
						map.put(key, sql);
					}
				}
			}
		}
		catch (Exception e) {
			if (logger.isInfoEnabled()) {
				logger.info("解析XML错误！" + e.toString());
				e.printStackTrace();
			}
		}
		
		return map;
	}
	
	@SuppressWarnings("unchecked")
	public static HashMap<String, String> readReportSqlNoTrim(String path, final String xpath) {
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			// 解析节点 getXml(path)
			List listx = getXml(path).selectNodes(xpath);// "/systemLoad/value"
			if (listx != null && !listx.isEmpty()) {

				// logger.debug("获取XML配置文件节点数为：" + listx.size());

				for (int i = 0; i < listx.size(); i++) {
					Element el = (Element) listx.get(i);
					String sql = el.getText();
					String key = el.attributeValue("key");
					if (key != null && !"".equals(key) && sql != null && !"".equals(sql)) {
						map.put(key, sql);
					}
				}
			}
		}
		catch (Exception e) {
			if (logger.isInfoEnabled()) {
				logger.info("解析XML错误！" + e.toString());
				e.printStackTrace();
			}
		}
		
		return map;
	}

}
